
#include <HeightMap.h>


HeightMap::HeightMap(char *inFilename, int inNumVertsPerRow, int inNumVertsPerCol, int inCellSpacing, float inHeightScale)
{
	mFilename = new char[strlen(inFilename) + 1];
	strcpy(mFilename,inFilename);
	mNumVertsPerRow = inNumVertsPerCol - 1;
	mNumVertsPerCol = inNumVertsPerCol - 1;
	mNumVertices = mNumVertsPerCol * mNumVertsPerRow;
	mCellSpacing = inCellSpacing;
	mHeightScale = inHeightScale;
	mWidth = mNumVertsPerRow * mCellSpacing;
	mDepth = mNumVertsPerCol * mCellSpacing;
	
}

bool HeightMap::ReadFile()
{
	std::vector<unsigned char> inData(mNumVertices); 
	FILE *file = NULL;
	errno_t res = fopen_s(&file,mFilename,"r");
	if(file == NULL)
		return false;

	fseek(file,0,SEEK_END);
	long fileSize = ftell(file);
	fseek(file,0, SEEK_SET);
	byte *pBuffer = new byte[mNumVertices];
	fread(pBuffer,fileSize,1,file);

/*	std::fstream inFile("d:\\crate.bmp",std::ios_base::binary);
	if(inFile == 0)
		return false;
	inFile.read((char *)&inData, inData.size());
	inFile.close();
*/
	mHeightMap.resize(sizeof(pBuffer));
	std::vector<int>::size_type ddd= mHeightMap.capacity();

	for(int i=0;i<mNumVertices;i++)
		mHeightMap[i] = pBuffer[i] * mHeightScale;

	return true;
}

int HeightMap::GetHeightMapEntry(int row, int col)
{
	int i = mHeightMap.size();
	return mHeightMap[row * mNumVertsPerRow + col];
}

void HeightMap::SetHeightMapEntry(int row, int col, int value)
{
	mHeightMap[row * mNumVertsPerCol + col] = value;
}
/*
glBegin(GL_TRIANGLES);								// Drawing Using Triangles
		glColor3f(1.0f,0.0f,0.0f);						// Set The Color To Red
		glVertex3f( 0.0f, 1.0f, 0.0f);					// Top
		glColor3f(0.0f,1.0f,0.0f);						// Set The Color To Green
		glVertex3f(-1.0f,-1.0f, 0.0f);					// Bottom Left
		glColor3f(0.0f,0.0f,1.0f);						// Set The Color To Blue
		glVertex3f( 1.0f,-1.0f, 0.0f);					// Bottom Right
	glEnd();

	*/

void HeightMap::Draw()
{
	int startX = -mWidth/2;
	int startZ = mDepth;
	glBegin(GL_LINES);
	for(int row = 0  ; row < 100; row+=10)
	{
		glColor3f(0.0f,1.0f,0.0f);
		glVertex3f(row-50.0f,0.0f,0.0f);
		glColor3f(0.0f,1.0f,0.0f);
		glVertex3f(row -50.0f,0.0f, 40.0f);
	}
	glEnd();
}

HeightMap::~HeightMap()
{
	delete[] mFilename;
}
